package com.jackstraw.jack_base.datasource.zookeeper.service;

import com.jackstraw.jack_base.datasource.common.entity.SnowflakeIdGenerator;
import com.jackstraw.jack_base.datasource.common.entity.enums.BusinessNameInterFace;
import com.jackstraw.jack_base.datasource.common.service.impl.AbstractSnowflakeIdService;
import com.jackstraw.jack_base.datasource.zookeeper.bean.ZookeeperRouting;
import com.jackstraw.jack_base.datasource.zookeeper.bean.ZookeeperTemplate;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Component;

/**
 * zookeeper雪花算法生成
 */
@Component
public class ZookeeperSnowflakeIdServiceImpl extends AbstractSnowflakeIdService<ZookeeperRouting> {

    /**
     * 获取SnowflakeIdGenerator，若没有初始化，则进行初始化
     *
     * @param businessNameInterFace 业务名称
     * @return
     */
    public SnowflakeIdGenerator snowflakeIdGenerator(BusinessNameInterFace businessNameInterFace) {
        String businessName = businessNameInterFace.getBusinessName();
        SnowflakeIdGenerator snowflakeIdGenerator = this.getSnowflakeIdGeneratorMap().get(businessName);
        if (ObjectUtils.isEmpty(snowflakeIdGenerator)) {
            synchronized (businessName) {
                snowflakeIdGenerator = this.getSnowflakeIdGeneratorMap().get(businessName);
                if (ObjectUtils.isEmpty(snowflakeIdGenerator)) {
                    ZookeeperTemplate zookeeperTemplate = this.getDataSourceRouting().tenantDefaultTemplate();
                    //生成顺序的workid
                    String workId = zookeeperTemplate.createNode(this.getWorkNodeMakerPathPrefix(), businessName, CreateMode.EPHEMERAL_SEQUENTIAL);
                    workId = workId.replace(this.getWorkNodeMakerPathPrefix().concat("/").concat(businessName), "");
                    snowflakeIdGenerator = SnowflakeIdGenerator.build(Long.parseLong(workId));
                    this.getSnowflakeIdGeneratorMap().put(businessName, snowflakeIdGenerator);
                }
            }
        }
        return snowflakeIdGenerator;

    }

}
